//
//  BuyListViewController.m
//  ShrimpCrowdordering
//
//  Created by 郑洲 on 2018/7/27.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "BuyListViewController.h"

#import "PayViewController.h"
#import "MoreDetailViewController.h"
#import "LogisticsMessageViewController.h"
#import "OrderDetailViewController.h"
#import "ShareURLView.h"
#import "BuyListCell.h"
#import <AlipaySDK/AlipaySDK.h>

@interface BuyListViewController ()<UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIView *moveLine;
@property (nonatomic, strong) UIButton *selectBtn;
@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, assign) NSInteger state;
@property (nonatomic, strong) UILabel *totalNum;
@property (nonatomic, strong) NSMutableArray  *dataArray;
@property (nonatomic, strong) NSMutableArray  *pagesArray;
@property (nonatomic, strong) NSMutableArray  *currentPageArray;
@property (nonatomic, strong) ShareURLView    *shareUrlView;

@end

@implementation BuyListViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"购买清单";
    self.view.backgroundColor = RGB_COLOR(244, 244, 244);
    
    _totalNum =[[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(0), ScreenX375(0), ScreenX375(65), ScreenX375(27))];
    _totalNum.text = @"23个订单";
    _totalNum.font = Kfont(14);
    _totalNum.textColor = REXADECIMALCOLOR(@"#f21934");
    _totalNum.textAlignment = NSTextAlignmentCenter;
    _totalNum.layer.borderWidth = 1;
    _totalNum.layer.cornerRadius = 13.5;
    _totalNum.layer.borderColor = REXADECIMALCOLOR(@"#f21934").CGColor;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_totalNum];
    
    self.state = 0;
    self.dataArray = [NSMutableArray array];
    self.pagesArray = [NSMutableArray array];
    self.currentPageArray = [NSMutableArray array];
    for (int i = 0; i < 5; i++) {
        NSMutableArray *array = [NSMutableArray array];
        [self.dataArray addObject:array];
        [self.pagesArray addObject:@"1"];
        [self.currentPageArray addObject:@"1"];
    }
    [self setTopBar];
    [self setUI];
}

-(void)viewWillDisappear:(BOOL)animated{
    [_shareUrlView removeFromSuperview];
    _shareUrlView = nil;
}

-(void)setShareURLView{
    if (!_shareUrlView) {
        _shareUrlView = [[ShareURLView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    }
    [kKeyWindow addSubview:_shareUrlView];
    __weak __typeof(self) weakSelf = self;

    _shareUrlView.hiddenClick = ^{
        [weakSelf.shareUrlView removeFromSuperview];
    };
}

- (void)setTopBar {
    UIView *topBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(35))];
    topBar.backgroundColor = TABLEVIEW_BACKGROUNDCOLOR;
    [self.view addSubview:topBar];
    
    NSArray *nameArr = @[@"全部",@"代付款",@"待发货",@"待收货",@"已完成"];
    for (int i = 0; i < nameArr.count; i++) {
        UIButton *typeBtn = [[UIButton alloc] initWithFrame:CGRectMake(i * SCREEN_WIDTH / 5, 0, SCREEN_WIDTH / 5, ScreenX375(35))];
        [typeBtn setTitle:nameArr[i] forState:UIControlStateNormal];
        [typeBtn setTitleColor:FONTCOLOR_BLACK forState:UIControlStateNormal];
        typeBtn.titleLabel.font = Kfont(13);
        typeBtn.tag = 100 + i;
        if (i == 0) {
            typeBtn.selected = YES;
            _selectBtn = typeBtn;
        }
        [typeBtn addTarget:self action:@selector(typeClick:) forControlEvents:UIControlEventTouchUpInside];
        [topBar addSubview:typeBtn];
    }
    
    self.moveLine = [[UIView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH / 5 - ScreenX375(40)) / 2, ScreenX375(35) - 2, ScreenX375(40), 2)];
    self.moveLine.backgroundColor = REXADECIMALCOLOR(@"#f21934");
    [topBar addSubview:self.moveLine];
}

- (void)typeClick:(UIButton *)button {
    _selectBtn.selected = NO;
    button.selected = YES;
    _selectBtn = button;
    _state = button.tag - 100;
    if (button.tag == 100 + _state && [_dataArray[_state] count] == 0) {
        BaseTableView *tableView = [self.view viewWithTag:200 + _state];
        [tableView.mj_header beginRefreshing];
    }
    [UIView animateWithDuration:0.3 animations:^{
        self.moveLine.frame = CGRectMake((SCREEN_WIDTH / 5 - ScreenX375(40)) / 2 + (button.tag - 100) * SCREEN_WIDTH / 5, ScreenX375(35) - 2, ScreenX375(40), 2);
    }];
    [_scrollView setContentOffset:CGPointMake((button.tag - 100) * SCREEN_WIDTH, 0) animated:YES];
}

- (void)setUI {
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, ScreenX375(35), SCREEN_WIDTH, SCREEN_HEIGHT - ScreenX375(35))];
    _scrollView.showsVerticalScrollIndicator = false;
    _scrollView.showsHorizontalScrollIndicator = false;
    _scrollView.pagingEnabled = true;
    _scrollView.delegate = self;
    _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH * 5, 0);
    [self.view addSubview:_scrollView];
    
    for (int i = 0; i < 5; i++) {
        BaseTableView *tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(i * SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - ScreenX375(35))];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.tag = 200 + i;
        tableView.rowHeight = ScreenX375(207);
        [_scrollView addSubview:tableView];
        
        UIView *nullView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - ScreenX375(35))];
        nullView.tag = 300 + i;
        nullView.backgroundColor = [UIColor whiteColor];
        nullView.hidden = YES;
        [tableView addSubview:nullView];
        
        UIImageView *nullImage = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - ScreenX375(66)) / 2, ScreenX375(100), ScreenX375(66), ScreenX375(66))];
        nullImage.image = ImageWithName(@"图标");
        [nullView addSubview:nullImage];
        
        UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, ScreenX375(187), SCREEN_WIDTH, ScreenX375(18))];
        noteLabel.text = @"您还没有相关的订单";
        noteLabel.textAlignment = NSTextAlignmentCenter;
        noteLabel.font = Kfont(13);
        noteLabel.textColor = REXADECIMALCOLOR(@"#000000");
        [nullView addSubview:noteLabel];
        
        UILabel *noteLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(0, ScreenX375(215), SCREEN_WIDTH, ScreenX375(17))];
        noteLabel2.text = @"可以去看看哪些想买的";
        noteLabel2.textAlignment = NSTextAlignmentCenter;
        noteLabel2.font = Kfont(12);
        noteLabel2.textColor = REXADECIMALCOLOR(@"#7f7f7f");
        [nullView addSubview:noteLabel2];
        
        __weak __typeof(self)weakSelf = self;
        tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf.currentPageArray replaceObjectAtIndex:weakSelf.state withObject:@"1"];
            
            NSString *url = [NSString stringWithFormat:@"%@api/orderList",REQUESTHEADER];
            NSString *status = @"";
            switch (weakSelf.state) {
                case 0:
                    status = @"";
                    break;
                case 1:
                    status = @"0";
                    break;
                case 2:
                    status = @"1";
                    break;
                case 3:
                    status = @"2";
                    break;
                case 4:
                    status = @"5";
                    break;
                    
                default:
                    break;
            }
            NSDictionary *dict = @{@"userId":kNSUDefaultReadKey(@"userId"),@"page":@"1",@"status":status};
            
            [HttpManager postHttpRequestByGet:url andParameter:dict success:^(id successResponse) {
                NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
                if ([status isEqualToString:@"200"]) {
                    [tableView.mj_header endRefreshing];
                    NSError *error;
                    [weakSelf.dataArray[weakSelf.state] removeAllObjects];
                    [weakSelf.pagesArray replaceObjectAtIndex:weakSelf.state withObject:[NSString stringWithFormat:@"%@",successResponse[@"data"][@"pages"]]];
                    for (NSDictionary *dic in successResponse[@"data"][@"list"]) {
                        OrderModel *model = [[OrderModel alloc] initWithDictionary:dic error:&error];
//                        [weakSelf.dataArray[weakSelf.state] addObject:model];
                    }
                    if ([weakSelf.pagesArray[weakSelf.state] isEqualToString:weakSelf.currentPageArray[weakSelf.state]]) {
                        tableView.mj_footer.hidden = YES;
                    }
                    NSMutableArray *array = weakSelf.dataArray[weakSelf.state];
                    UIView *nullView = [weakSelf.view viewWithTag:tableView.tag + 100];
                    if (array.count == 0) {
                        nullView.hidden = NO;
                    }else {
                        nullView.hidden = YES;
                    }
                    if (weakSelf.state == 0) {
                        weakSelf.totalNum.text = [NSString stringWithFormat:@"%@个订单",successResponse[@"data"][@"total"]];
                    }
                    [tableView reloadData];
                    
                }else{
                    [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
                }
            } andFailure:^(id failureResponse) {
                [tableView.mj_header endRefreshing];
                [HttpManager showFail];
            }];
        }];
        
        tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            NSInteger page = [weakSelf.currentPageArray[weakSelf.state] integerValue];
            [weakSelf.currentPageArray replaceObjectAtIndex:weakSelf.state withObject:[NSString stringWithFormat:@"%ld",page + 1]];
            
            NSString *url = [NSString stringWithFormat:@"%@api/orderList",REQUESTHEADER];
            NSString *status = @"";
            switch (weakSelf.state) {
                case 0:
                    status = @"";
                    break;
                case 1:
                    status = @"0";
                    break;
                case 2:
                    status = @"1";
                    break;
                case 3:
                    status = @"2";
                    break;
                case 4:
                    status = @"5";
                    break;
                    
                default:
                    break;
            }
            NSDictionary *dict = @{@"userId":kNSUDefaultReadKey(@"userId"),@"page":weakSelf.currentPageArray[weakSelf.state],@"status":status};
            
            [HttpManager postHttpRequestByGet:url andParameter:dict success:^(id successResponse) {
                NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
                if ([status isEqualToString:@"200"]) {
                    [tableView.mj_footer endRefreshing];
                    NSError *error;
                    [weakSelf.pagesArray replaceObjectAtIndex:weakSelf.state withObject:[NSString stringWithFormat:@"%@",successResponse[@"data"][@"pages"]]];
                    for (NSDictionary *dic in successResponse[@"data"][@"list"]) {
                        OrderModel *model = [[OrderModel alloc] initWithDictionary:dic error:&error];
                        [weakSelf.dataArray[weakSelf.state] addObject:model];
                    }
                    if ([weakSelf.pagesArray[weakSelf.state] isEqualToString:weakSelf.currentPageArray[weakSelf.state]]) {
                        tableView.mj_footer.hidden = YES;
                    }
                    [tableView reloadData];
                    
                }else{
                    [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
                }
            } andFailure:^(id failureResponse) {
                [tableView.mj_footer endRefreshing];
                [HttpManager showFail];
            }];
        }];
        
        if (i == 0) {
            [tableView.mj_header beginRefreshing];
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_dataArray[tableView.tag - 200] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BuyListCell *cell = [BuyListCell cellWithTableView:tableView andIndexPath:indexPath];
    cell.orderModel = _dataArray[tableView.tag - 200][indexPath.row];
    OrderModel *model = _dataArray[tableView.tag - 200][indexPath.row];
    cell.logisticsClick = ^{
        LogisticsMessageViewController *vc = [[LogisticsMessageViewController alloc] init];
        vc.acceptAdress = [NSString stringWithFormat:@"%@%@%@  %@  %@",model.recProvince,model.recCity,model.recArea,model.recName,model.recAddress];
        vc.orderNum = model.ordNum;
        [self.navigationController pushViewController:vc animated:YES];
    };
    cell.seeLinkClick = ^{
        [self setShareURLView];
        [self.shareUrlView setUrl:model.link andPassword:model.downloadPassword];
    };
    cell.noteClick = ^{
        [HttpManager showNoteMsg:@"已提醒卖家发货"];
    };
    cell.payClick = ^{
        PayViewController *vc = [[PayViewController alloc] init];
        vc.picUrl = model.proPic;
        vc.proName = model.proName;
        vc.price = model.proPrice;
        vc.ordNum = model.ordNum;
        [self.navigationController pushViewController:vc animated:YES];
    };
    cell.sureClick = ^{
        NSString * url = [NSString stringWithFormat:@"%@api/confirm",REQUESTHEADER];
        NSDictionary * parameter = @{@"userId":kNSUDefaultReadKey(@"userId"),@"ordNum":model.ordNum};
        [HttpManager showWait];
        [HttpManager postHttpRequestByPost:url andParameter:parameter success:^(id successResponse) {
            [HttpManager hideWait];
            NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
            if ([status isEqualToString:@"200"]) {
                [HttpManager showNoteMsg:@"确认收货成功"];
                [tableView.mj_header beginRefreshing];
            }else{
                [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
            }
        } andFailure:^(id failureResponse) {
            [HttpManager showFail];
        }];
    };
    cell.buyClick = ^{
        MoreDetailViewController *vc = [[MoreDetailViewController alloc] init];
        vc.proId = model.Id;
        [self.navigationController pushViewController:vc animated:YES];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    OrderModel *model = _dataArray[tableView.tag - 200][indexPath.row];
    OrderDetailViewController *vc = [[OrderDetailViewController alloc] init];
    vc.status = model.status;
    vc.ordId = model.Id;
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == _scrollView) {
        NSInteger index = scrollView.contentOffset.x / SCREEN_WIDTH;
        
        UIButton *button = [self.view viewWithTag:index + 100];
        _selectBtn.selected = NO;
        button.selected = YES;
        _selectBtn = button;
        [UIView animateWithDuration:0.3 animations:^{
            self.moveLine.frame = CGRectMake((SCREEN_WIDTH / 5 - ScreenX375(40)) / 2 + (button.tag - 100) * SCREEN_WIDTH / 5, ScreenX375(35) - 2, ScreenX375(40), 2);
        }];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == _scrollView) {
        NSInteger index = scrollView.contentOffset.x / SCREEN_WIDTH;
        
        UIButton *button = [self.view viewWithTag:index + 100];
        _selectBtn.selected = NO;
        button.selected = YES;
        _selectBtn = button;
        _state = button.tag - 100;
        if (button.tag == 100 + _state && [_dataArray[_state] count] == 0) {
            BaseTableView *tableView = [self.view viewWithTag:200 + _state];
            [tableView.mj_header beginRefreshing];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return ScreenX375(219);
}


@end
